<?php
/**** 6/28/12 Element.php v3.0 ****/

class Element {
	private $parent;
	protected $tag;
	public $prefix;
	protected $contents = Array();
	public $attributes;
//	public $namespace;
	
	public function __construct($tag, $content = NULL, Array $attributes = NULL) {
		if(is_array($tag)) {
			$this->prefix = array_shift($tag);
			$this->tag = array_shift($tag);
		} else {
			$this->tag = $tag;
		}
		if($content) {
			array_push($this->contents, $content);
		}
		if($attributes) {
			$this->attributes = $attributes;
		}
	}
	
	public function __toString() {
		$attributes = '';
		$c = NULL;
		if($this->attributes) {
			if(is_array($this->attributes)) {
				foreach($this->attributes as $attr => $value) {
					$attributes .= " $attr=\"$value\"";
				}
			}
			else {
				return '';
			}
		}
		if(!$this->contents) {
			return ($this->prefix) ? "<$this->prefix:$this->tag$attributes />" : "<$this->tag$attributes />";
		}
		if(is_array($this->contents)) {
				foreach($this->contents as $item) {
					$c .= ($item instanceof Element) ? $item : htmlspecialchars($item);
				}
		}
		else {
			$c = ($this->contents instanceof Element) ? $this->contents : htmlspecialchars($this->contents);
		}
		return ($this->prefix) ? "<$this->prefix:$this->tag$attributes>$c</$this->prefix:$this->tag>" : "<$this->tag$attributes>$c</$this->tag>";
	}
	
	public function appendTo(Element $parent) {
		if(!$this->parent) {
			$this->parent = $parent;
		}
		array_push($parent->contents, $this);
		return $this;
	}
	
	public function content() {
		if(func_num_args() > 0) {
			foreach(func_get_args() as $arg) {
				array_push($this->contents, $arg);
			}
		}
		return $this->contents;
	}
	
	public function getParent() {
		return $this->parent;
	}
}

?>
